package com.example.yiwei.crm.view.activity.JYCoordingActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.BaseActivity;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.dockDao;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.dockDaoImpl;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.data.GetAreData;
import com.example.yiwei.crm.data.GetContact;
import com.example.yiwei.crm.data.GetCustumer;
import com.example.yiwei.crm.data.GetDock;
import com.example.yiwei.crm.entity.dockingEntity;
import com.example.yiwei.crm.entity.jgsxEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;
import com.example.yiwei.crm.util.ZhengZhe;
import com.example.yiwei.crm.view.Class.GetLocationData;
import com.example.yiwei.crm.view.activity.areActivity.ProvinceActivity;
import com.example.yiwei.crm.view.activity.jdjycooractivity.JYJDAddManyiduActivity;
import com.example.yiwei.crm.view.activity.jtCustomer.JDcoorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

//协作建议版本新增合作客户的界面
public class AddCoorActivity extends BaseActivity{
    private EditText edit_docking_name,  edit_docking_mechanism, edit_department,
            edit_professional_title, edit_phone_number, edit_additional, edit_xadress, edit_jd;
    private TextView txt_address,txt_title,txt_address1,txt_dw;
    private ArrayAdapter adapter2;
    String msg;
    private Button btn_show,btn_show1;
    private ImageView  img_commit;
    List<String> jgsx_list=new ArrayList<>();
    private JSONObject mJsonObj;
    private String Filename;
    private List<String> name_list = new ArrayList<>();
    List<managerEntity> managerList;
    private ArrayAdapter adapter1;
    private String managerName;
    private int manager_id;
    String manager_name;
    Spinner spinner_jgsx;
    SharedPreferences sp;
    dockingEntity docking;
    String jgsx;
    int i = 0;
    int jgsx_id;
    String tx;
    String pid;
    String pname = "";
    String cid;
    String cname = "";
    String aid;
    String aname = "";
    String version;
    Button commit;
    List<jgsxEntity> jgsxEntities;
    dockingEntity dockingEntity;
    StringBuffer sb;
    private String lo1,la1,lo2,la2;
    String address="";
    private String jd,wd,jd1,wd1,address1;
    int code;
    String str;

    private ImageView img_search,img_luru,img_me,img_tj,img_back,img_xinghao;
boolean isFirstLoc = true;// 是否首次定位
//public BDLocationListener myListener = new BDLocationListener() {
//    public void onReceiveLocation(BDLocation location) {
//
//        // map view 销毁后不在处理新接收的位置
//        if (location == null )
//            return;
//        MyLocationData locData = new MyLocationData.Builder()
//                .accuracy(location.getRadius())
//                // 此处设置开发者获取到的方向信息，顺时针0-360
//                .direction(100).latitude(location.getLatitude())
//                .longitude(location.getLongitude()).build();
//        sb = new StringBuffer(256);
////            sb.append("time : ");
//        sb.append(location.getTime()+",");
//        sb.append(location.getLocationDescribe()+",");// 位置语义化信息
//        sb.append(location.getLatitude()+",");    //获取纬度信息
//        sb.append(location.getLongitude());    //获取经度信息
//        LatLng ll = new LatLng(location.getLatitude(),
//                location.getLongitude());
//        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 16);   //设置地图中心点以及缩放级别
//    }
//};
public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_coor);
        txt_title = (TextView) findViewById(R.id.healt_education_add_txt_title);
        if ("update".equals(getIntent().getStringExtra("tag"))) {
            txt_title.setText("修改合作客户");
        }
        //保存在本地的信息
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        img_xinghao= (ImageView) findViewById(R.id.dingwei_xinghao);
        img_back= (ImageView) findViewById(R.id.detailed_doc_img_back);
        txt_dw= (TextView) findViewById(R.id.txt_dingwei);
        img_search= (ImageView) findViewById(R.id.item_image_cx);
        spinner_jgsx= (Spinner) findViewById(R.id.coor_add_jgsx);
        img_luru= (ImageView) findViewById(R.id.item_image_lr);
        img_tj= (ImageView) findViewById(R.id.item_image_tj);
        img_me= (ImageView) findViewById(R.id.item_image_w);
        img_commit = (ImageView) findViewById(R.id.health_education_add_img_commit);
        btn_show = (Button) findViewById(R.id.health_education_add_btn_show);
        btn_show1 = (Button) findViewById(R.id.health_education_add_btn_show1);
        txt_address = (TextView) findViewById(R.id.health_education_add_txt_address);
        txt_address1 = (TextView) findViewById(R.id.health_education_add_txt_dingwei);
        edit_docking_name = (EditText) findViewById(R.id.health_education_add_edit_docking_name);
        edit_docking_mechanism= (EditText) findViewById(R.id.health_education_add_edit_docking_mechanism);
        edit_department = (EditText) findViewById(R.id.health_education_add_edit_department);
        edit_professional_title = (EditText) findViewById(R.id.health_education_add_edit_professional_title);
        edit_phone_number = (EditText) findViewById(R.id.health_education_add_edit_phone_number);
        edit_additional = (EditText) findViewById(R.id.health_education_add_edit_additional);
        edit_xadress = (EditText) findViewById(R.id.health_education_add_edit_xadress);
        edit_jd = (EditText) findViewById(R.id.health_education_add_edit_jd);
        commit = (Button) findViewById(R.id.add_coor_btn);
//        PackageManager manager = this.getPackageManager();
//        PackageInfo info = null;
//        try {
//            info = manager.getPackageInfo(this.getPackageName(), 0);
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        code = info.versionCode;
//        Toast.makeText(this, ""+code, Toast.LENGTH_SHORT).show();
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener( myListener );
        initLocation(); //设置定位参数

        //必填项的判断条件
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (txt_address.getText().toString().equals("")||edit_docking_name.getText().toString().equals("")||txt_address1.getText().equals("")) {
                    Toast.makeText(AddCoorActivity.this, "请填写必填项！", Toast.LENGTH_SHORT).show();
                }else if (!"".equals(edit_phone_number.getText().toString())&& !ZhengZhe.phone(edit_phone_number.getText().toString())){
                    Toast.makeText(AddCoorActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                }else {
                    add();
                }
            }
        });
        btn_show1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLocationClient.stop();
                Intent intent=new Intent(AddCoorActivity.this,AddressChangeActivty.class);
                intent.putExtra("address",txt_address1.getText().toString());
                GetLocationData.address=null;
                GetLocationData.wd=null;
                GetLocationData.jd=null;
                startActivity(intent);
            }
        });
        if ("update".equals(getIntent().getStringExtra("tag"))) {
            //修改时输入框赋值的方法
//            btn_show1.setVisibility(View.VISIBLE);
//            img_xinghao.setVisibility(View.VISIBLE);
            showMessage();
            txt_dw.setText("修改定位");
        }else{
//            btn_show1.setVisibility(View.GONE);
//            img_xinghao.setVisibility(View.GONE);
            mLocationClient.start(); // 开始定位
        }
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //所属区域返回
        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddCoorActivity.this, ProvinceActivity.class);
                GetAreData.pname = null;
                GetAreData.aname = null;
                GetAreData.cname = null;
                GetAreData.pid = null;
                GetAreData.cid = null;
                GetAreData.aid = null;
                startActivity(intent);
            }
        });
        //返回查寻页面
      img_search.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              Intent intent=new Intent(AddCoorActivity.this,JDcoorActivity.class);
              intent.putExtra("ii","ii");
              startActivity(intent);
              finish();
          }
      });
        //返回录入界面
        img_luru.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(AddCoorActivity.this,JDcoorActivity.class);
                startActivity(intent);
                finish();
            }
        });
        //返回我的界面
        img_me.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(AddCoorActivity.this,JDcoorActivity.class);
                intent.putExtra("me","me");
                startActivity(intent);
                finish();
            }
        });
        //返回统计界面
        img_tj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(AddCoorActivity.this,JDcoorActivity.class);
                intent.putExtra("tt","tt");
                startActivity(intent);
                finish();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                String json = object.toString();
                dockDao dockDao = new dockDaoImpl();
                //机构属性下拉列表
                jgsxEntities = dockDao.queryJGSXMessage(baseClass.find_jgsx_url, json);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        jgsx_list.add("");
                        if (jgsxEntities!=null){
                            for (int i3 = 0;i3<jgsxEntities.size();i3++){
                                jgsx_list.add(jgsxEntities.get(i3).getJgsx());
                            }
                            adapter2 = new ArrayAdapter(AddCoorActivity.this,R.layout.spinner_display_style,R.id.txtvwSpinner, jgsx_list);
                            adapter2.setDropDownViewResource(R.layout.spinner_dropdown_style);
                            spinner_jgsx.setAdapter(adapter2);
                            spinner_jgsx.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                    if (position>0){
                                        //机构属性
                                        jgsx=jgsxEntities.get(position-1).getJgsx();
                                        //机构属性ID
                                        jgsx_id=jgsxEntities.get(position-1).getJgsx_id();
                                    }
                                }
                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                }
                            });
                        }
                        //修改时机构属性的Spinner赋值
                        if ("update".equals(getIntent().getStringExtra("tag"))){
                            dockingEntity=GetDock.get();
                            for (int i = 0;i<jgsxEntities.size();i++){
                                if (jgsxEntities.get(i).getJgsx_id()==dockingEntity.getMechanism_attribute_id()){
                                   spinner_jgsx.setSelection(i+1);
                                }
                            }
                        }
                    }
                });
            }
        }).start();
    }
    //新增合作客户的方法
    public void add(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                docking = GetDock.get();
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                try {
                    if ("update".equals(getIntent().getStringExtra("tag"))) {
                        docking = GetDock.get();
                        object.put("KXA01", docking.getDocking_id());
                        object.put("addoredit", "edit");
                    } else {
                        object.put("addoredit", "add");
                        object.put("KXA15", sp.getString("CID03",null));
                        object.put("KXA28", sp.getString("CID01",null));
                    }
                    if ("update".equals(getIntent().getStringExtra("tag"))) {
                        if (docking!=null) {
                            if (docking.getDingwei() != null) {
                                if (txt_address1.getText().toString().equals(docking.getDingwei())) {
                                    object.put("KXA33", docking.getJingdu());
                                    object.put("KXA34", docking.getWd());
                                    object.put("KXA35", docking.getDingwei());
                                } else {
                                    object.put("KXA33", jd);
                                    object.put("KXA34", wd);
                                    object.put("KXA35", address);
                                }
                            }
                        }
                    }else{
                        object.put("KXA33", jd);
                        object.put("KXA34", wd);
                        object.put("KXA35", address);
                    }


                    object.put("KXA02", edit_docking_name.getText().toString());
                    object.put("KXA03", edit_docking_mechanism.getText().toString());
                    object.put("AKN01", jgsx_id);
                    object.put("KXA05", edit_department.getText().toString());
                    object.put("KXA06", edit_professional_title.getText().toString());
                    object.put("KXA08", edit_phone_number.getText().toString());
                    object.put("KXA29", txt_address.getText().toString());
                    object.put("REK01", edit_additional.getText().toString());
//                                object.put("KXA17", pid);
                    object.put("CID03", sp.getString("CID03", null));
                    if (!pname.equals("")){
                        object.put("KXA17", pid);
                        object.put("KXA18",pname);
                    }
                    if (!cname.equals("")){
                        object.put("KXA19", cid);
                        object.put("KXA20",cname);
                    }
                    if (!aname.equals("")){
                        object.put("KXA21", aid);
                        object.put("KXA22",aname);
                    }
                    object.put("KXA27", edit_jd.getText().toString());
                    object.put("KXA29", edit_xadress.getText().toString());
                    String json = object.toString();
                    String result;
                    result = NetWorkUtils.getCount(baseClass.edit_coordianation_URL, json);
                    final JSONObject object1 = new JSONObject(result);
                    String boolen = object1.getString("ifsuccess");
                    if ("true".equals(boolen)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if ("update".equals(getIntent().getStringExtra("tag"))) {
                                    Toast.makeText(AddCoorActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                                }else{
                                    Toast.makeText(AddCoorActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                                }
                                finish();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    msg=object1.getString("msg");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                if ("update".equals(getIntent().getStringExtra("tag"))){
                                    Toast.makeText(AddCoorActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                                }else {
                                    if ("".equals(msg)) {
                                        Toast.makeText(AddCoorActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(AddCoorActivity.this, msg, Toast.LENGTH_SHORT).show();
                                    }
                                }

                            }
                        });

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    //给控件赋值的方法
    public void showMessage() {
        docking = GetDock.get();
        edit_department.setText(docking.getDepartment());
        edit_docking_name.setText(docking.getDocking_name());
        edit_docking_mechanism.setText(docking.getDocking_mechanism());
        edit_professional_title.setText(docking.getProfessional_title());
        edit_phone_number.setText(docking.getPhone_number());
        if (docking.getAname() != null && docking.getPname() != null && docking.getCname() != null) {
            txt_address.setText(docking.getPname() + docking.getCname() + docking.getAname());
        }
        txt_address1.setText(docking.getDingwei());
        edit_additional.setText(docking.getAddtional_remark());
        edit_xadress.setText(docking.getAddress());
        edit_jd.setText(docking.getJd());
    }
    //返回页面的刷新方法
    @Override
    protected void onRestart() {
        super.onRestart();
        if (GetAreData.pname!=null){
            pid = GetAreData.pid;
            pname = GetAreData.pname;
            cid = GetAreData.cid;
            cname = GetAreData.cname;
            aid = GetAreData.aid;
            aname =GetAreData.aname;
            txt_address.setText(pname+cname+aname);
        }
        if (GetLocationData.address!=null&&!"".equals(GetLocationData.address)){
            jd=GetLocationData.jd;
            wd=GetLocationData.wd;
            address=GetLocationData.address;
            txt_address1.setText(address);
        }
    }
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //获取定位结果
            sb = new StringBuffer(256);
            sb.append(location.getTime()+",");
        sb.append(location.getLocationDescribe()+",");// 位置语义化信息
        sb.append(location.getLatitude()+",");    //获取纬度信息
        sb.append(location.getLongitude());    //获取经度信息
                if (sb!=null) {
                str = sb.toString();
                String[] strs = str.split(",");
                jd = strs[3];
                wd = strs[2];
                address = strs[1];
                if ("在郑和雕像附近".equals(address)) {
                    if ("update".equals(getIntent().getStringExtra("tag"))) {

                    }else{
                        Toast.makeText(AddCoorActivity.this, "请检查网络，并重新定位", Toast.LENGTH_SHORT).show();
                        txt_address1.setText("");
                    }

                }else if (address.equals("null")){
                   txt_address1.setText("");
                } else{
                    txt_address1.setText(address);
                }
//                sb=null;
            }else{
                    txt_address1.setText("");
                }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
    }
}
